package org.fly.utils.code;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

/**
 * Created by rongzhao.zhu on 2015/3/20.
 */
public class VelocityUtil {
    private final static Logger logger = LoggerFactory.getLogger(VelocityUtil.class);

    static VelocityEngine engine = null;
    static {
        Properties p = new Properties();
        InputStream is = null;
        try {
            p.put("input.encoding","utf-8");
            p.put("output.encoding","utf-8");
            p.put("resource.loader","class");
            p.put("class.resource.loader.description","Velocity Classpath Resource Loader");
            p.put("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            p.put("class.resource.loader.cache",false);
            p.put("class.resource.loader.modificationCheckInterval","2");
            p.put("velocimacro.permissions.allow.inline",true);
            p.put("velocimacro.permissions.allow.inline.to.replace.global",true);
            p.put("velocimacro.permissions.allow.inline.local.scope",false);
            p.put("velocimacro.context.localscope",true);
            p.put("runtime.log.logsystem.class","org.apache.velocity.runtime.log.Log4JLogChute");
            p.put("runtime.log.logsystem.log4j.logger","opb.velocity");
            engine = new VelocityEngine(p);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("init velocityutl", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     *根据模板文件获取对应整个文件的转义
     * @param templateName
     * @param contextMap
     * @return
     */
    public static String getRenderResult(String templateName, Map<String, Object> contextMap)throws Exception {
        Template template = engine.getTemplate(templateName, "utf-8");
        Context context = new VelocityContext(contextMap);
        StringWriter writer = new StringWriter();
        template.merge(context, writer);
        return writer.toString();
    }

    /**
     * 解析模板内容
     *
     * @param templateContent 模板内容
     * @param contextMap 上下文变量
     * @param key 模板KEY值LoadingCache
     * @return 解析完的内容
     */
    public static String getRenderResult(String templateContent, Map<String, Object> contextMap, String key)throws Exception {
        Context context = new VelocityContext(contextMap);
        StringWriter writer = new StringWriter();
        engine.evaluate(context, writer, key, templateContent);
        return writer.toString();
    }
}
